﻿using BP.Plugin.Monitor.Application.Features.SystemLogs.DTOs;
using Core.Attributes;
using Core.Extensions;
using Core.Interfaces.Users;
using Core.Models;
using Core.Persistence;
using Core.SystemLogs;
using Gridify;
using Gridify.EntityFramework;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace BP.Plugin.Monitor.Application.Features.SystemLogs.Queries.PaginationQuery;

[NoLogging]
public class SystemLogsWithPaginationQuery : GridifyQuery, IRequest<PaginatedData<SystemLogDto>>
{
}

public class SystemLogsWithPaginationQueryHandler :
         IRequestHandler<SystemLogsWithPaginationQuery, PaginatedData<SystemLogDto>>
{
    private readonly ILogDbContext _db;
    private readonly ICurrentUserService _currentUserService;

    public SystemLogsWithPaginationQueryHandler(
        ILogDbContext db, ICurrentUserService currentUserService)
    {
        _db = db;
        _currentUserService = currentUserService;
    }

    public async Task<PaginatedData<SystemLogDto>> Handle(SystemLogsWithPaginationQuery request, CancellationToken cancellationToken)
    {
        var username = _currentUserService.Name;
        var isSuperAdmin = _currentUserService.IsSuperAdmin;
        return (await _db.SystemLogs
            .AsNoTracking()
            .Where(x => !string.IsNullOrWhiteSpace(x.TraceId))
            .WhereIf(!isSuperAdmin, x => x.UserName == username)
            .GridifyAsync(request, cancellationToken))
            .ToPaginatedList<SystemLog, SystemLogDto>(request.Page, request.PageSize);
    }
}
